package com.project.controller;

import com.project.bean.UserBean;
import com.project.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author lyl
 * description:用户controller
 */
@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private IUserService iUserService;


    /**
     * 用户登录
     *
     * @param request
     * @param userBean
     * @return
     */
    @RequestMapping("login")
    public String login(HttpServletRequest request, UserBean userBean) {
        UserBean us = iUserService.login(userBean.getUsername(), userBean.getPassword());
        if (us == null) {
            //如果为null则返回no
            return "no";
        }
        //如果不为null则进行网址的跳转并添加session记录
        setUserSession(request, us);
        //返回用户对象，方便进行等级判断
        return us.getLevel();
    }

    /**
     * 获取当前用户session
     *
     * @param request
     * @return
     */
    @RequestMapping("getUserSession")
    public Object getUserSession(HttpServletRequest request) {
        UserBean userBean = (UserBean) request.getSession().getAttribute("userBean");
        System.out.println(userBean);
        if (userBean == null) {
            return "no";
        }
        return userBean;
    }


    /**
     * 将当前用户上传至session中
     *
     * @param userBean
     */
    public void setUserSession(HttpServletRequest request, UserBean userBean) {
        HttpSession session = request.getSession();
        session.setAttribute("userBean", userBean);
    }

    /**
     * 用户退出，摧毁session
     *
     * @param request
     * @return
     */
    @RequestMapping("outAccount")
    public String outAccount(HttpServletRequest request) {
        //摧毁当前session
        request.getSession().invalidate();
        return "ok";
    }

}
